<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

include 'header.php';
require_once 'db.php';
require_once 'common.php';

// get parameters from HTTP_REQUEST
$hash = $_REQUEST['str']; // defined in web server's rewrite rule
$url = !empty($_POST['url']) ? $_POST['url'] : ""; // may be NULL
$sql = "";

// not shortizen strings
if (empty($hash)) {
    // plain page 
    if (empty($url)) {
        // show form
        include 'form.php';
        // process from
    } else {
        // check URL is vaild
        if (!checkURL($url)){
            redirectTo("/");
        }
        // insert & display
        $hash_gen = rand_string(5);
        $sql = "insert into url (`from`,`to`) values('" . $url . "','" . $hash_gen . "')";
        $success = $mysqli->query($sql);
        if ($success) {
            echo "Shortizen! URL is " . $_SERVER['HTTP_HOST'] . "/" . $hash_gen;
        }
    }
// process string contain in HTTP_REQUEST
} else {
    $sql = "select `from` from url where `to` = '" . $hash . "'";
    $result = $mysqli->query($sql);
    $rows = $result->num_rows;
    if ($rows == 0) {
        echo "No url related here.";
    } else {
        $row = $result->fetch_array(MYSQLI_NUM);
        redirectTo($row[0]);
    }
}
$mysqli->close();

include 'footer.php';
?>
